﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using MinistryStandardPlatformWeb.Models;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb.Controllers.RealTime;

namespace MinistryStandardPlatformWeb.Controllers.Reports
{
    [MenuAuthorized("43")]
    public class TotalMileageStatisticsController : Controller
    {
        //
        // GET: /TotalMileageStatistics/

        private MSPGpsDataContext context = new MSPGpsDataContext();
        private MSPDataContext context1 = new MSPDataContext();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Data(string vehicles, int pageIndex = 1)
        {
            if (Session["SearchData"] != null)
            {
                return PartialView((Session["SearchData"] as List<MileageStatistics>).ToPagedList(pageIndex, CommonDictionary.PageSize));
            }

            //得到要查询的车辆id的list
            List<string> vehiclesList = vehicles.Split(';').ToList();

            //获取车辆的所属单位
            var unit = from v in context1.InfoVehicle
                       from u in context1.InfoUnit
                       where vehiclesList.Contains(v.SIM) &&
                       v.ParentUnitId == u.UNITID
                       select new MileageStatistics()
                       {
                           VehicleId = v.VehicleId,
                           ParentUnitName = u.UNITNAME,
                           Sim = v.SIM,
                       };
            List<MileageStatistics> units = unit.ToList();
            MileageStatistics emptyMileage=new MileageStatistics()
            {
                Mileage=string.Empty
            };
            DateTime now=DateTime.Now;

            //当查询结果中的某辆车的里程数据为空，则到上一个月的数据库中查询，直到所有的车辆都有里程数据或者已经没有上一个月的数据库为止
            while (units.Contains(emptyMileage, new MileageStatisticsMileageEquality()) && RealTimeGet.getCheckDbExitsOrNot(now.ToString(CommonDictionary.DateTimeStrFormat)) == "1")
            {
                var endMileage = from b in context.GpsBasic
                                 where vehiclesList.Contains(b.simId)
                                 group b by b.vehicleId into bg
                                 let last = bg.Max(t => t.recordtime)
                                 from r in bg
                                 where r.recordtime == last
                                 select new 
                                 {
                                     Sim = r.simId,
                                     VehicleId = r.vehicleId,
                                     Mileage = r.mileage == -1 ? r.gpsmileage : r.mileage,
                                     StatisticsTime = r.recordtime
                                 };

                List<string> paramaters = new List<string>();
                for (int i = 0; i < vehiclesList.Count; i++)
                {
                    paramaters.Add(vehiclesList[i].ToVarcharSqlParam());
                }
                paramaters.Add("-1");

                string endMileageJsonStr = RealTimeGet.getReportFromGeoBase(CommonFunctions.GetLoginUser().UserId, CommonFunctions.GetSQL(endMileage, paramaters), now.ToString(CommonDictionary.DateStrFormat), now.ToString(CommonDictionary.DateStrFormat), "0");
                List<MileageStatistics> endMileages = CommonFunctions.JsonStrToObject<List<MileageStatistics>>(endMileageJsonStr);

                //填充里程数据
                var v1 = from n in units
                         join m in endMileages
                         on n.VehicleId equals m.VehicleId
                         into nm
                         from nmd in nm.DefaultIfEmpty()
                         select new MileageStatistics()
                         {
                             Sim = n.Sim,
                             VehicleId = n.VehicleId,
                             Mileage = nmd == null ? "" : nmd.Mileage,
                             StatisticsTime = nmd == null ? "" : nmd.StatisticsTime,
                             ParentUnitName = n.ParentUnitName
                         };

                units = v1.ToList();

                now = now.AddMonths(-1);
            }

            Session["SearchData"] = units;
            return PartialView(units.ToPagedList(pageIndex, CommonDictionary.PageSize));
        }

        public ActionResult ExportData()
        {
            CommonController controller = new CommonController();
            Dictionary<string, string> title = new Dictionary<string, string>();
            title.Add("VehicleId", "车牌号");
            title.Add("Sim", "SIM卡号");
            title.Add("ParentUnitName", "所属单位");
            title.Add("StatisticsTime", "统计时间");
            title.Add("Mileage", "里程（公里）");
            string fileName = "总里程统计";
            if (Session["SearchData"] != null)
            {
                return controller.ListToExcel<MileageStatistics>((Session["SearchData"] as IEnumerable<MileageStatistics>).ToList(), title, fileName,Server);
            }
            else
            {
                ViewBag.Message = "数据已过期，请重新查询";
                return View("ActionResult");
            }
        }
    }
}
